<?php


namespace app\index\controller;


use app\index\model\ActionRole;
use app\index\model\Customer;
use app\index\model\CustomerOrder;
use app\index\model\Order;
use app\index\model\OrderItem;
use app\index\model\OrderPayment;
use app\index\model\Product;
use app\index\model\ProductPurHistory;
use app\index\model\User;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;
use think\response\Json;

class Finance extends BaseController
{
    protected $request;
    protected $validate;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
    }

    /**
     * getReportParam
     * 获取报表页基础配置数据
     * @url /report/param
     * @method POST
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Asira
     * @date 2020/12/22
     */
    public function getReportParam(): Json
    {
        $date=date('Y-m-d',strtotime('-1 days'));
        $start_date=[$date,$date];
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();
        ['action_role'=>$action_role,'group'=>$search_group,'search_user'=>$search_user]=ActionRole::checkUserActionRole('order');
        return json(['code'=>0,'date'=>$start_date,'user_list'=>$user_list,'group_list'=>$group_list]);
    }

    /**
     * getReportCostData
     * 获取报表成本花费数据
     * @url /report/cost
     * @method POST
     * @request array date
     * @request array user
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Asira
     * @date 2020/12/22
     */
    public function getReportCostData(): Json
    {
        $date=input('post.date/a');
        $user=input('post.user/a');
        $group=input('post.group');
        $time=ceil((strtotime($date[1])-strtotime($date[0]))/60/60/24)+1;

        ['status'=>$status,'result'=>$result]=ProductPurHistory::getStockOutPurCost(['create_time'=>$date]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $pur_cost=$result['cost'];
        ['status'=>$status,'result'=>$result]=Order::getPaidOrderPaidCost(['create_time'=>$date,'user'=>$user,'group_id'=>$group]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $ship_cost=0;
        if(is_array($result['cost'])){
            foreach ($result['cost'] as $key=>$value){
                $ship_cost+=$value['price'];
            }
        }

        $ship_cost *= 0.2;
        $ship_cost_rmb=round($ship_cost*usdExchange,2);

        $diverse_cost=$time*1000;

        $total_cost=round($ship_cost_rmb+$diverse_cost+$pur_cost,2);
        return json(['code'=>0,'cost'=>$total_cost,'diverse_cost'=>$diverse_cost,'pur_cost'=>round($pur_cost,2),'ship_cost'=>round($ship_cost,2)]);
    }


    /**
     * getReportSalesData
     * 获得销售额
     * @url /report/sales
     * @method POST
     * @request array date 日期
     * @request array user 用户
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Asira
     * @date 2020/12/28
     */
    public function getReportSalesData(): Json
    {
        $date=input('post.date/a');
        $user=input('post.user/a');
        $group=input('post.group');

        ['status'=>$status,'result'=>$result]=CustomerOrder::getCustomerOrderSales(['create_time'=>$date,'user'=>$user,'group_id'=>$group]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $total_sales=round($result['total_sales'],2);
        $sales_data=$result['sales_data'];

        return json(['code'=>0,'total_sales'=>$total_sales,'sales_data'=>$sales_data,'action_role'=>$result['action_role']]);
    }

    /**
     * getPaidCost
     * 获得回款
     * @url /report/paid
     * @method POST
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Asira
     * @date 2021/1/14
     */
    public function getPaidCost(): Json
    {
        $date=input('post.date/a');
        $user=input('post.user/a');
        $group=input('post.group');

        ['status'=>$status,'result'=>$result]=Order::getPaidOrderPaidCost(['create_time'=>$date,'user'=>$user,'group_id'=>$group]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        $cost=$result['cost'];
        $total_cost = 0;
        if(is_array($cost)) {
            foreach ($cost as $key => $value) {
                if ($value['total_price']) {
                    $cost[$key]['rate'] =round($value['price'] / $value['total_price'],2);
                } else {
                    $cost[$key]['rate'] = 0;
                }
                $total_cost += $value['price'];
            }
        }
        return json(['code'=>0,'cost'=>$cost,'total_cost'=>round($total_cost,2),'action_role'=>$result['action_role']]);
    }

    /**
     * 获取单人的回款清单
     * create by yhb on 2021/3/22 17:26
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPaidDetail()
    {
        $date=input('post.date/a');
        $user=input('post.user/a');
        $group=input('post.group');
        $userId=input('post.id');
        $orderClass = new Order();
        ['status'=>$status,'result'=>$result] = $orderClass->getOrderDetail(['create_time'=>$date,'user'=>$user,'group_id'=>$group,'id'=>$userId]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'order_detail'=>$result['order_detail']]);
    }

    /**
     * 获取单人的销售额清单
     * create by yhb on 2021/4/6 18:16
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getSalesDetail()
    {
        $date=input('post.date/a');
        $user=input('post.user/a');
        $group=input('post.group');
        $userId=input('post.id');
        $customerClass = new Customer();
        ['status'=>$status,'result'=>$result] = $customerClass->getSalesDetail(['create_time'=>$date,'user'=>$user,'group_id'=>$group,'id'=>$userId]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'sales_detail'=>$result['sales_detail']]);
    }

    /**
     * 获取每月销售额
     * create by yhb on 2021/3/17 13:33
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getSellData()
    {
        $user=input('post.user');
        $group=input('post.group');
        $date=input('post.date');

        $customerOrderClass = new CustomerOrder();
        ['status'=>$status,'result'=>$result]=$customerOrderClass->getSellingPrice(['date'=>$date,'user'=>$user,'group_id'=>$group]);

        $result['data_list'] = ['type'=>'line','title'=>['text'=>'每月销售额'],'labels'=>collection($result['data_list']['monthDay']),'datasets'=>[['data'=>$result['data_list']['ySemData'],'label'=>'',]]];

        return json(['code'=>0,'data_list'=>$result['data_list'], 'action_role'=>$result['action_role']]);
    }

    /**
     * getProfitParam
     * 获取利润页基本数据
     * @url /profit/param
     * @method POST
     * @return Json
     * @author Asira
     * @date 2021/1/14
     */
    public function getProfitParam(): Json
    {
        $product_type=Product::$product_type;
        return json(['code'=>0,'product_type'=>$product_type]);
    }

    /**
     * getProfitData
     * 获取利润列表
     * @url /profit/list
     * @method POST
     * @request array date 日期
     * @request array product_type 商品类型
     * @request array sort 排序方式
     * @request array pageIndex 页码
     * @request array pageSize 页面大小
     * @return Json
     * @author Asira
     * @date 2021/1/14
     */
    public function getProfitData(): Json
    {
        $date=input('post.date/a');
        $product_type=input('post.product_type');
        $sort=input('post.sort/a');
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        $sort_param=[
            'column'=>$sort['prop']??'amount',
            'desc'=>$sort['order']==='ascending'?'asc':'desc',
        ];
        if($product_type==='1'){
            ['status'=>$status,'result'=>$result]=OrderItem::getSalesAmount(['create_time'=>$date,'type'=>$product_type],$page_param,$sort_param);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
        }elseif($product_type==='2'){
            ['status'=>$status,'result'=>$result]=ProductPurHistory::getSalesAmount(['create_time'=>$date,'type'=>$product_type],$page_param,$sort_param);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
        }else{
            return json(['code'=>1,'msg'=>'type 错误']);
        }

        $total_sales=$result['total_sales'];
        $sales_data=$result['sales_data'];
        return json(['code'=>0,'pageCount'=>$result['count'],'total_sales'=>$total_sales,'data'=>$sales_data]);
    }
}